<?php
namespace Home\Controller;
use Think\Controller;
class DepartmentController extends Controller {


    public function Department(){
    	$m_department = M('Department');

    	$departmentList = $m_department->order('id asc')->select();

    	$this->assign('departmentList',$departmentList);

        $this->display();
    }


    //新增部门
    public function ctrl_AddNewDepartment(){
    	if (IS_AJAX) {
    		$department_name = trim($_REQUEST['department_name']);

    		$m_department = M('Department');

    		$where['name'] = $department_name;

    		$departmentInfo = $m_department->where($where)->find();
    		if ($departmentInfo['id']) {
    			$this->ajaxReturn(array(
	                'code'=>101,
	                'msg' => '该部门已经存在，无法添加'
	            ));
    		}else{

    			$add['name'] = $department_name;
    			$result = $m_department->add($add);
    			if ($result) {
    				$this->ajaxReturn(array(
		                'code'=>100,
		                'msg' => '添加成功',
		                'data'=>array(
		                	'id'=>$result,
		                	'name'=>$department_name,
		            		),
		            ));
    			}else{
    				$this->ajaxReturn(array(
		                'code'=>101,
		                'msg' => '部门添加失败'
		            ));
    			}
    		}


    	}else{
    		$this->redirect('Common/BadRequest');
    	}

    }



    //删除部门
    public function ctrl_DeleteDepartment(){
    	if (IS_AJAX) {
    		$id = $_REQUEST['id'];

    		$m_department = M('Department');

    		$where['id'] = $id;

    		$departmentInfo = $m_department->where($where)->find();
    		if ($departmentInfo['id']) {
    			$result = $m_department->where($where)->delete();
    			if ($result) {
    				$this->ajaxReturn(array(
		                'code'=>100,
		                'msg' => '删除成功'
		            ));
    			}else{
    				$this->ajaxReturn(array(
		                'code'=>101,
		                'msg' => '删除失败'
		            ));
    			}

    		}else{
    			$this->ajaxReturn(array(
	                'code'=>102,
	                'msg' => '该部门已经删除，请勿重复操作'
	            ));
    		}


    	}else{
    		$this->redirect('Common/BadRequest');
    	}
    }
}